import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/profile/nickname_setting/nickname_setting_page_logic.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';

/*
 * 昵称设置页面
 */
class NicknameSettingPage extends StatefulWidget {
  const NicknameSettingPage({super.key});

  @override
  State<NicknameSettingPage> createState() => _NicknameSettingPageState();
}

class _NicknameSettingPageState extends State<NicknameSettingPage> {
  @override
  void initState() {
    super.initState();

    context.read<NicknameSettingPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<NicknameSettingPageLogic>(
      builder: (context, logic, child) {
        return Scaffold(
          appBar: _buildAppBar(context, logic),
          body: _buildMainBody(context, logic),
        );
      },
    );
  }

  // 构建AppBar
  AppBar _buildAppBar(BuildContext context, NicknameSettingPageLogic logic) {
    final fontSize =
        (Theme.of(context).appBarTheme.titleTextStyle?.fontSize ?? 20) - 2;
    return AppBar(
      title: const Text(AppStrings.updateNickname),
      actions: [
        TextButton(
          onPressed: logic.controller.text.isNotEmpty ? _okAction : null,
          child: Text(AppStrings.ok, style: TextStyle(fontSize: fontSize)),
        ),
      ],
    );
  }

  // 构建主体内容
  Widget _buildMainBody(BuildContext context, NicknameSettingPageLogic logic) {
    return Column(
      children: [
        const SizedBox(height: 15),
        TextField(
          decoration: InputDecoration(
            // labelText: AppStrings.nickname,
            // labelStyle: const TextStyle(fontSize: 20),
            hintText: AppStrings.nicknameHint,
            hintStyle: const TextStyle(fontSize: 20),
            contentPadding: const EdgeInsets.symmetric(horizontal: 15),
            suffix: Text('${logic.leftCount}'),
          ),
          controller: logic.controller,
          focusNode: logic.focusNode,
          autofocus: true,
          maxLength: 20,
          buildCounter:
              (
                context, {
                required currentLength,
                required isFocused,
                maxLength,
              }) {
                return null;
              },
        ),
      ],
    );
  }

  void _okAction() async {
    final logic = context.read<NicknameSettingPageLogic>();
    final newName = logic.controller.text.trim();
    if (newName.isEmpty) {
      EasyLoading.showError(AppStrings.nicknameEmpty);
      return;
    }
    logic.focusNode.unfocus(); // 失去焦点
    logic.updateNickname(newName).then((value) {
      if (mounted && value) {
        Navigator.of(context).pop();
      }
    });
  }
}
